<template>
	<div>
		<el-select v-model="province" placeholder="请选择省份">
			<el-option v-for="item in areas" :key="item.code" :value="item.code" :label="item.name"></el-option>
		</el-select>
		<el-select :disabled="!province" style="margin: 0 10px" v-model="city" placeholder="请选择城市">
			<el-option v-for="item in selectCity" :key="item.code" :value="item.code" :label="item.name"></el-option>
		</el-select>
		<el-select :disabled="!province || !city" v-model="area" placeholder="请选择区域">
			<el-option v-for="item in selectArea" :key="item.code" :value="item.code" :label="item.name"></el-option>
		</el-select>
	</div>
</template>

<script lang="ts" setup name='chooseArea'>
	import {
		ref,
		watch
	} from "vue"

	import allAreas from '../lib/pca-code.json'

	let province = ref('')
	let city = ref('')
	let area = ref('')
	let areas = ref(allAreas)
	let selectCity = ref([])
	let selectArea = ref([])

	let emits = defineEmits(['change'])

	watch(() => province.value, val => {
		if (val) {
			let cities = areas.value.find(item => item.code === province.value).children
			selectCity.value = cities
		}
		city.value = ''
		area.value = ''
	})

	watch(() => city.value, val => {
		if (val) {
			let area = selectCity.value.find(item => item.code === city.value).children
			selectArea.value = area
		}
		area.value = ''
	})

	watch(() => area.value, val => {
		if (val) {
			let provinceData = {
				code: province.value,
				name: allAreas.find(item => item.code === province.value).name
			}
			let cityData = {
				code: city.value,
				name: city.value && selectCity.value.find(item => item.code === city.value).name
			}
			let areaData = {
				code: val,
				name: val && selectArea.value.find(item => item.code === area.value).name
			}
			emits('change', {
				province: provinceData,
				city: cityData,
				area: areaData
			})
		}
	})
</script>

<style scoped>

</style>
